<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">设备位置总览</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshDevices">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
      
      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-statistic title="设备总数" :value="deviceList.length">
            <template slot="prefix">
              <i class="el-icon-monitor" style="color: #409eff"></i>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="在线设备" :value="onlineDeviceCount">
            <template slot="prefix">
              <i class="el-icon-success" style="color: #67c23a"></i>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="离线设备" :value="offlineDeviceCount">
            <template slot="prefix">
              <i class="el-icon-error" style="color: #f56c6c"></i>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="有位置信息" :value="devicesWithLocation">
            <template slot="prefix">
              <i class="el-icon-location" style="color: #e6a23c"></i>
            </template>
          </el-statistic>
        </el-col>
      </el-row>
      
      <!-- 地图 -->
      <device-map 
        :devices="deviceList" 
        height="600px"
      />
    </el-card>
  </div>
</template>

<script>
import { listDeviceData } from "@/api/emqx/deviceDetails"
import DeviceMap from "@/components/DeviceMap"

export default {
  name: "DeviceMapView",
  components: {
    DeviceMap
  },
  data() {
    return {
      deviceList: [],
      loading: false
    }
  },
  computed: {
    onlineDeviceCount() {
      return this.deviceList.filter(device => device.connectStatus).length
    },
    offlineDeviceCount() {
      return this.deviceList.filter(device => !device.connectStatus).length
    },
    devicesWithLocation() {
      return this.deviceList.filter(device => device.longitude && device.latitude).length
    }
  },
  created() {
    this.getDeviceList()
  },
  methods: {
    // 获取设备列表
    getDeviceList() {
      this.loading = true
      listDeviceData({}).then(response => {
        this.deviceList = response.rows || response.data || response
      }).catch(error => {
        console.error('获取设备数据失败:', error)
        this.$message.error('获取设备数据失败')
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 刷新设备数据
    refreshDevices() {
      this.getDeviceList()
      this.$message.success('设备数据已刷新')
    }
  }
}
</script>

<style scoped>
.box-card {
  border-radius: 8px;
}

.el-statistic {
  text-align: center;
}
</style>